package com.junt.library.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.junt.library.MediaSelector;
import com.junt.library.R;
import com.junt.library.model.Media;
import com.junt.library.widgets.CheckView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MediaAdapter extends RecyclerView.Adapter<MediaAdapter.MediaViewHolder> {

    private Context context;
    /**
     * 列表数据
     */
    private List<Media> medias;
    /**
     * 已选择的媒体集合
     */
    private List<Media> selectedMedias;

    public MediaAdapter(Context context) {
        this.context = context;
        medias = new ArrayList<>();
        selectedMedias = new ArrayList<>();
    }

    @NonNull
    @Override
    public MediaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MediaViewHolder(LayoutInflater.from(context).inflate(R.layout.item_media, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull final MediaViewHolder holder, int position) {
        final Media media = medias.get(position);
        MediaSelector.getInstance().getImageEngine().load(media.getUri(), holder.imageView);
        holder.checkBox.setChecked(media.isChecked());
        holder.checkBox.setOnCheckedChangeListener(new CheckView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CheckView buttonView, boolean isChecked) {
                if (isChecked) {
                    selectedMedias.add(media);
                } else {
                    selectedMedias.remove(media);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return medias.size();
    }

    public List<Media> getSelectedMedias() {
        return selectedMedias;
    }

    public void add(Media media) {
        medias.add(media);
        notifyItemInserted(medias.size() - 1);
    }

    public void setNewData(List<Media> newData) {
        if (equalList(medias,newData)){
            return;
        }
        medias.clear();
        medias.addAll(newData);
        notifyDataSetChanged();
    }

    public boolean equalList(List<Media> list1, List<Media> list2) {
        return (list1.size() == list2.size()) && list1.containsAll(list2);
    }

    /**
     * 图片、视频的ViewHolder
     */
    class MediaViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView;
        private CheckView checkBox;

        public MediaViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            checkBox = itemView.findViewById(R.id.checkbox);
        }
    }
}
